﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml.Linq;
namespace Common.Xml
{
    public class XMLReader
    {
        internal static List<T_Table> GetTables()
        {
            List<T_Table> tables = new List<T_Table>();
            XElement doc = GetXElement();
            var petNames = from pn in doc.Descendants("table") select pn;
            foreach (var name in petNames)
            {
                T_Table table = new T_Table();
                table.TableName = name.Attribute("Name").Value;
                table.Description = name.Attribute("Description").Value;
                table.IsStatic = name.Attribute("Static").Value.Equals("True") ? true : false;
                tables.Add(table);
            }
            return tables;
        }

        internal static List<T_Field> GetFields(string tableName)
        {
            XElement doc = GetXElement();
            List<T_Field> fields = new List<T_Field>();
            var petNames = from pn in doc.Descendants("table") where pn.Attribute("Name").Value.Equals(tableName) select pn;
            foreach (var element in petNames.Elements("field"))
            {
                T_Field field = new T_Field();
                field.Attribute = element.Attribute("DataType").Value;
                field.Field = element.Value;
                field.FieldName = element.Attribute("Description").Value;
                field.TableName = tableName;
                fields.Add(field);
            }
            return fields;
        }

        private static XElement GetXElement()
        {
            Assembly assem = Assembly.GetExecutingAssembly();
            StringBuilder xmlFileName = new StringBuilder();
            xmlFileName.Append(assem.GetName().Name);
            xmlFileName.Append("/xml/FileBuilder.xml");
            XElement doc = XElement.Load(xmlFileName.ToString());
            return doc;
        }
    }
}
